package org.abettor.nookinfo.view;

import org.abettor.nookinfo.R;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 * 页面跳转对话框
 * @author abettor
 *
 */
public class PageDialog extends Dialog
{
	private int totalPage;
	private int currentPage;
	private OnPageJumpListener onPageJumpListener;

	public PageDialog(Context context, int totalPage, int currentPage)
	{
		super(context);
		this.totalPage = totalPage;
		this.currentPage = currentPage;
		setCancelable(true);
		setOnCancelListener(new DialogInterface.OnCancelListener()
		{
			@Override
			public void onCancel(DialogInterface dialog)
			{
				dismiss();
			}
		});
	}

	@Override
	public void show()
	{
		setContentView(R.layout.page_dialog);
		TextView totalView = (TextView) findViewById(R.id.pageDialogTotal);
		String total = (String) totalView.getText();
		total = total.replace("REPL2", currentPage + "");
		if(totalPage <= 0)
		{
			total = total.replace("REPL1", getContext().getString(R.string.page_dialog_total_page_alt));
		}
		else
		{
			total = total.replace("REPL1", totalPage + "");
		}
		totalView.setText(total);

		((Button) findViewById(R.id.pageDialogButtonCancel)).setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				PageDialog.this.cancel();
			}
		});

		Button ok = (Button) findViewById(R.id.pageDialogButtonOk);
		if(onPageJumpListener == null)
		{
			ok.setOnClickListener(new View.OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					PageDialog.this.cancel();
				}
			});
		}
		else
		{
			ok.setOnClickListener(new View.OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					onPageJumpListener.onPageJump(PageDialog.this);
				}
			});
		}

		super.show();
	}

	/**
	 * 设置确定按钮相应事件监听器
	 * @param onPageJumpListener
	 */
	public void setOnPageJumpListener(OnPageJumpListener onPageJumpListener)
	{
		this.onPageJumpListener = onPageJumpListener;
	}

	/**
	 * 获取当前选择的页号
	 */
	public int getCurrentPage()
	{
		EditText editor = (EditText) findViewById(R.id.pageDialogValue);
		Editable editable = editor.getEditableText();
		if(editable == null)
		{
			return -1;
		}
		String str = editable.toString();
		if(str == null || str.length() <= 0)
		{
			return -1;
		}

		try
		{
			return Integer.parseInt(str);
		}
		catch(Exception e)
		{
			return -1;
		}
	}
}
